/**
 * 缓存管理
 */
const install = (Vue) => {
    const PREFIX_KEY = 'APP-STORAGE.'
    const storage = {
        /**
         * 设置缓存
         * @param {Object} key
         * @param {Object} data
         * @param {Object} duration 缓存有效时间，毫秒，从设置缓存开始计算，获取时判断
         */
        set: function(key, data, duration){
            const storageData = {
                data,
                setTime: (new Date()).getTime(),
                duration
            }
            uni.setStorageSync(PREFIX_KEY + key, storageData)
        },
        /**
         * 获取缓存
         * @param {Object} key
         * @return {Object} { setTime, duration, data }
         */
        get: function(key){
            const storageData = uni.getStorageSync(PREFIX_KEY + key)
            if(storageData){
                const { setTime, duration, data } = storageData
                // 设置过期时间，判断
                if(duration && (setTime + duration) < (new Date()).getTime()){
                    storage.clear(PREFIX_KEY + key)
                    return null
                }
                return storageData
            }else {
                return null
            }
        },
        /**
         * 清除缓存
         * @param {Object} key
         */
        clear: function(key){
            uni.clearStorageSync(PREFIX_KEY + key)
        }
    }
    
    //挂载到 $u 对象
	uni.$u.storage = storage
}

export default {
	install
}
